package us.codecraft.webmagic.selector;

import java.util.ArrayList;
import java.util.List;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.apache.commons.lang3.StringUtils;

/**
 * 自定义选择器，Groovy脚本，函数名：process，参数：上次接受的结果
 * 
 * @author Administrator
 *
 */
public class RouterSelector implements Selector {

    private Invocable inv;

    public RouterSelector(String source) {
        if (StringUtils.isNotBlank(source)) {
            ScriptEngineManager factory = new ScriptEngineManager();
            ScriptEngine engine = factory.getEngineByName("groovy");
            try {
                engine.eval(source);
            } catch (ScriptException e) {
                e.printStackTrace();
            }
            inv = (Invocable) engine;
        }
    }

    @Override
    public String select(String text) {
        try {
            return (String) inv.invokeFunction("process", text);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            return null;
        } catch (ScriptException e) {
            e.printStackTrace();
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<String> selectList(String text) {
        try {
            Object obj = inv.invokeFunction("process", text);
            if (obj instanceof List) {
                return (List<String>) inv.invokeFunction("process", text);
            }
            List<String> strings = new ArrayList<String>();
            String str = (String) inv.invokeFunction("process", text);
            strings.add(str);
            return strings;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            return null;
        } catch (ScriptException e) {
            e.printStackTrace();
            return null;
        }
    }

}
